<template>
  <div class="image-page">
    <!-- 图像生成表单 -->
    <div class="generate-section">
      <div class="section-header">
        <h2>🎨 AI图像生成</h2>
        <p>输入描述，让AI为您创造美丽的图像</p>
      </div>
      
      <form @submit.prevent="generateImage" class="generate-form">
        <div class="form-group">
          <label for="prompt">描述您想要生成的图像</label>
          <textarea 
            id="prompt"
            v-model="generateForm.prompt" 
            placeholder="请输入详细描述，例如：一幅美丽的山水风景画，蜡笔风格，阳光明媚..."
            rows="4"
            required
          ></textarea>
        </div>
        
        <div class="form-row">
          <div class="form-group">
            <label for="imageSize">图像尺寸</label>
            <select id="imageSize" v-model="generateForm.image_size">
              <option value="512x512">512x512</option>
              <option value="768x768">768x768</option>
              <option value="1024x1024">1024x1024</option>
            </select>
          </div>
          
          <div class="form-group">
            <label for="numImages">生成数量</label>
            <select id="numImages" v-model="generateForm.num_images">
              <option value="1">1张</option>
              <option value="2">2张</option>
              <option value="3">3张</option>
              <option value="4">4张</option>
            </select>
          </div>
        </div>
        
        <button type="submit" :disabled="generating" class="generate-btn">
          <span v-if="generating">🔄 生成中...</span>
          <span v-else>✨ 生成图像</span>
        </button>
      </form>
    </div>

    <!-- 图像列表 -->
    <div class="images-section">
      <div class="section-header">
        <h2>🖼️ 我的作品</h2>
        <button @click="loadImages" class="refresh-btn">🔄 刷新</button>
      </div>
      
      <div v-if="loading" class="loading">
        加载中...
      </div>
      
      <div v-else-if="imageList.length === 0" class="empty-state">
        <div class="empty-icon">🎨</div>
        <p>您还没有生成任何图像</p>
        <p>在上方输入描述开始创作吧！</p>
      </div>
      
      <div v-else class="images-grid">
        <div 
          v-for="image in imageList" 
          :key="image.id" 
          class="image-card"
        >
          <div class="image-container">
            <img 
              :src="getImageUrl(image.id)" 
              :alt="image.prompt"
              @error="handleImageError"
              loading="lazy"
            />
            <div class="image-overlay">
              <button @click="viewImage(image)" class="overlay-btn">🔍 查看</button>
              <button @click="deleteImage(image.id)" class="overlay-btn delete">🗑️ 删除</button>
            </div>
          </div>
          
          <div class="image-info">
            <p class="image-prompt">{{ truncateText(image.prompt, 60) }}</p>
            <div class="image-meta">
              <span class="status" :class="image.status">● {{ getStatusText(image.status) }}</span>
              <span class="size">{{ image.width }}x{{ image.height }}</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div v-if="totalPages > 1" class="pagination">
        <button 
          @click="changePage(currentPage - 1)" 
          :disabled="currentPage <= 1"
        >← 上一页</button>
        
        <span class="page-info">{{ currentPage }} / {{ totalPages }}</span>
        
        <button 
          @click="changePage(currentPage + 1)" 
          :disabled="currentPage >= totalPages"
        >下一页 →</button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { generate, images, proxy } from '@/api/image'

export default {
  name: 'Image',
  setup() {
    // 响应式数据
    const loading = ref(false)
    const generating = ref(false)
    const imageList = ref([])
    const currentPage = ref(1)
    const totalPages = ref(1)
    const pageSize = 10
    
    // 图片URL缓存（使用响应式对象代替Map）
    const imageUrls = reactive({})
    
    // 生成表单
    const generateForm = reactive({
      prompt: '',
      image_size: '1024x1024',
      num_images: 1
    })
    
    // 生成图像
    const generateImage = async () => {
      if (!generateForm.prompt.trim()) {
        alert('请输入图像描述')
        return
      }
      
      try {
        generating.value = true
        const result = await generate.create({
          prompt: generateForm.prompt,
          image_size: generateForm.image_size,
          num_images: generateForm.num_images
        })
        
        if (result.success) {
          alert('图像生成成功！')
          generateForm.prompt = ''
          loadImages() // 重新加载列表
        } else {
          alert('生成失败：' + result.error)
        }
      } catch (error) {
        console.error('生成错误:', error)
        alert('生成失败，请稍后重试')
      } finally {
        generating.value = false
      }
    }
    
    // 加载图像列表
    const loadImages = async () => {
      try {
        loading.value = true
        const result = await images.getList({
          page: currentPage.value,
          page_size: pageSize
        })
        
        console.log('图像列表加载结果:', result)
        
        if (result.success) {
          imageList.value = result.data.images
          totalPages.value = result.data.pagination.total_pages
          
          console.log('加载到的图像列表:', result.data.images)
          
          // 预加载所有图片
          for (const image of result.data.images) {
            console.log(`开始预加载图片 ID: ${image.id}`)
            loadImageUrl(image.id)
          }
        }
      } catch (error) {
        console.error('加载失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 加载单个图片URL
    const loadImageUrl = async (imageId) => {
      if (imageUrls[imageId]) {
        return // 已经加载过了
      }
      
      try {
        console.log(`开始加载图片 ${imageId}`)
        const response = await proxy.getImage(imageId)
        
        // 检查响应类型
        if (response && response.data) {
          const blob = new Blob([response.data], { type: 'image/jpeg' })
          const blobUrl = URL.createObjectURL(blob)
          imageUrls[imageId] = blobUrl
          console.log(`图片 ${imageId} 加载成功:`, blobUrl)
        } else {
          console.error(`图片 ${imageId} 响应数据为空`)
          imageUrls[imageId] = 'error'
        }
      } catch (error) {
        console.error(`加载图片 ${imageId} 失败:`, error)
        // 设置一个错误标记
        imageUrls[imageId] = 'error'
      }
    }
    
    // 获取图片URL（同步函数，用于模板）
    const getImageUrl = (imageId) => {
      const url = imageUrls[imageId]
      if (url && url !== 'error') {
        return url
      }
      // 如果还没加载，触发异步加载
      if (!imageUrls[imageId]) {
        loadImageUrl(imageId)
      }
      // 返回占位符
      return ''
    }
    
    // 删除图像
    const deleteImage = async (imageId) => {
      if (!confirm('确定要删除这张图像吗？')) return
      
      try {
        await images.delete(imageId)
        alert('删除成功')
        loadImages()
      } catch (error) {
        alert('删除失败')
      }
    }
    
    // 查看图像详情
    const viewImage = (image) => {
      const imageUrl = imageUrls[image.id]
      if (imageUrl && imageUrl !== 'error') {
        window.open(imageUrl, '_blank')
      } else {
        alert('图片还在加载中，请稍后再试')
      }
    }
    
    // 分页
    const changePage = (page) => {
      currentPage.value = page
      loadImages()
    }
    
    // 工具函数
    const truncateText = (text, maxLength) => {
      return text.length > maxLength ? text.slice(0, maxLength) + '...' : text
    }
    
    const getStatusText = (status) => {
      const statusMap = {
        'pending': '待处理',
        'processing': '生成中',
        'completed': '已完成',
        'failed': '生成失败'
      }
      return statusMap[status] || status
    }
    
    const handleImageError = (event) => {
      event.target.src = ''
    }
    
    // 组件挂载时加载数据
    onMounted(() => {
      loadImages()
    })
    
    // 组件卸载时清理Blob URLs
    const cleanupBlobUrls = () => {
      for (const [id, url] of Object.entries(imageUrls)) {
        if (url !== 'error') {
          URL.revokeObjectURL(url)
        }
      }
      // 清空对象
      Object.keys(imageUrls).forEach(key => {
        delete imageUrls[key]
      })
    }
    
    return {
      loading,
      generating,
      imageList,
      currentPage,
      totalPages,
      generateForm,
      generateImage,
      loadImages,
      getImageUrl,
      deleteImage,
      viewImage,
      changePage,
      truncateText,
      getStatusText,
      handleImageError,
      cleanupBlobUrls
    }
  }
}
</script>

<style scoped>
.image-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.section-header {
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-header h2 {
  font-size: 1.5rem;
  color: #8B7355;
  margin: 0;
}

.section-header p {
  color: #6b7280;
  margin: 4px 0 0 0;
}

.generate-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 32px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.generate-form {
  max-width: 600px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #374151;
}

.form-group textarea,
.form-group select {
  width: 100%;
  padding: 12px;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  font-size: 14px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.generate-btn {
  background: linear-gradient(135deg, #8B7355, #A3826B);
  color: white;
  border: none;
  padding: 14px 28px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.generate-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(139, 115, 85, 0.3);
}

.generate-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.images-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.refresh-btn {
  background: #f3f4f6;
  border: 1px solid #d1d5db;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.refresh-btn:hover {
  background: #e5e7eb;
}

.loading, .empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #6b7280;
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 16px;
}

.images-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.image-card {
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.image-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0,0,0,0.15);
}

.image-container {
  position: relative;
  aspect-ratio: 1;
  overflow: hidden;
}

.image-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 12px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.image-container:hover .image-overlay {
  opacity: 1;
}

.overlay-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  background: white;
  color: #374151;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.overlay-btn:hover {
  transform: scale(1.05);
}

.overlay-btn.delete {
  background: #ef4444;
  color: white;
}

.image-info {
  padding: 16px;
}

.image-prompt {
  font-size: 14px;
  color: #374151;
  margin: 0 0 8px 0;
  line-height: 1.4;
}

.image-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #6b7280;
}

.status {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 11px;
}

.status.completed { background: #dcfce7; color: #166534; }
.status.processing { background: #fef3c7; color: #92400e; }
.status.failed { background: #fee2e2; color: #dc2626; }
.status.pending { background: #f3f4f6; color: #4b5563; }

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #e5e7eb;
}

.pagination button {
  padding: 8px 16px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  background: white;
  cursor: pointer;
  transition: all 0.2s ease;
}

.pagination button:hover:not(:disabled) {
  background: #f9fafb;
}

.pagination button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  color: #6b7280;
  font-size: 14px;
}

@media (max-width: 768px) {
  .form-row {
    grid-template-columns: 1fr;
  }
  
  .images-grid {
    grid-template-columns: 1fr;
  }
  
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}
</style>